package com.party.jackclientandroid.ui_order;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.OrderService;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.OrderDetail;
import com.party.jackclientandroid.bean.User;
import com.party.jackclientandroid.bean.UserOrderExtraDetail;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.event.RefundEvent;
import com.party.jackclientandroid.loadviewhelper.help.OnLoadViewListener;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.AddCommentActivity;
import com.party.jackclientandroid.ui_home.activity.DiscountPayBillActivity;
import com.party.jackclientandroid.ui_home.activity.ShopDetailActivity;
import com.party.jackclientandroid.utils.PhoneUtil;
import com.party.jackclientandroid.utils.TimeUtil;
import com.party.jackclientandroid.view.dialog.QRCodeDialog;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 订单详情-待使用
 */
public class OrderDetailWaitUseActivity extends BaseActivityTitle {
    @BindView(R.id.whole_layout)
    LinearLayout whole_layout;
    @BindView(R.id.shop_name_tv)
    TextView shop_name_tv;
    @BindView(R.id.shop_address_tv)
    TextView shop_address_tv;
    @BindView(R.id.add_order_time_tv)
    TextView add_order_time_tv;
    @BindView(R.id.user_phone_tv)
    TextView user_phone_tv;
    @BindView(R.id.num_tv)
    TextView num_tv;
    @BindView(R.id.single_price_tv)
    TextView single_price_tv;
    @BindView(R.id.real_price_tv)
    TextView real_price_tv;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.goods_name_tv)
    TextView goods_name_tv;
    @BindView(R.id.apply_refund_btn)
    Button apply_refund_btn;
    @BindView(R.id.coupon_type_tv)
    TextView coupon_type_tv;
    @BindView(R.id.rl_merchant)
    RelativeLayout rl_merchant;
    @BindView(R.id.ll_goto_bill)
    LinearLayout ll_goto_bill;
    @BindView(R.id.qr_code_iv)
    ImageView qr_code_iv;

    private OrderService orderService;
    private OrderDetail orderDetail;
    private String order_id;
    private List<UserOrderExtraDetail> userOrderExtraDetailList = new ArrayList<>();
    private CommonAdapter<UserOrderExtraDetail> commonAdapter;
    private String goodsTitle;
    private String orderCode;
    private boolean applyRefundBtnCanClick = true;
//    private Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail_wait_use);
        receivePassDataIfNeed(getIntent());
        initData();
    }

    protected void receivePassDataIfNeed(Intent intent) {
        order_id = intent.getStringExtra("order_id");
    }

    protected void initData() {
        setMiddleText("订单详情");
        orderService = new OrderService(this);
        initView();
        helper = new LoadViewHelper(whole_layout);
        helper.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                loadData();
            }
        });
        helper.showLoading();
        loadData();
    }

    public void initView() {
        commonAdapter = new CommonAdapter<UserOrderExtraDetail>(mActivity, R.layout.item_order_detail_coupon_code, userOrderExtraDetailList) {
            @Override
            protected void convert(ViewHolder viewHolder, final UserOrderExtraDetail item, int position) {
                if (item.getType() == 2 && item.getType() == 1) {
                    ll_goto_bill.setVisibility(View.GONE);
                }
                TextView coupon_code_tv = viewHolder.getView(R.id.coupon_code_tv);
                Button add_comment_btn = viewHolder.getView(R.id.add_comment_btn);
                ImageView qr_code_iv = viewHolder.getView(R.id.qr_code_iv);
                coupon_code_tv.setText(item.getOrderCode());
                if (item.getOrderState() == 4) {//已完成
                    qr_code_iv.setVisibility(View.GONE);
                    add_comment_btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mActivity, AddCommentActivity.class);
                            intent.putExtra("shopId", orderDetail.getShopId());
                            intent.putExtra("orderId", item.getId());
                            startActivity(intent);
                        }
                    });
                } else {
                    if (item.getType() == Constant.GOODS_TYPE_REPLACE_MONEY || item.getType() == Constant.GOODS_TYPE_SECOND_KILL) {
                        add_comment_btn.setVisibility(View.GONE);
//                        qr_code_iv.setVisibility(View.GONE);
                        qr_code_iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (dupCommit()) return;
                                /*Intent intent = new Intent(mActivity, WatchCouponQRCodeActivity2.class);
                                intent.putExtra("orderCode", item.getOrderCode());
                                startActivity(intent);*/
                                Bitmap mBitmap = CodeUtils.createImage(item.getOrderCode(), 400, 400, null);
                                DialogController.showQRCodeDialog(mActivity, mBitmap);
                            }
                        });
                    } else if (item.getType() == Constant.GOODS_TYPE_GROUP_BUY || item.getType() == Constant.GOODS_TYPE_SPELLING_GROUP) {
                        add_comment_btn.setVisibility(View.GONE);
                        qr_code_iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (dupCommit()) return;
                                /*Intent intent = new Intent(mActivity, WatchCouponQRCodeActivity2.class);
                                intent.putExtra("orderCode", item.getOrderCode());
                                startActivity(intent);*/
                                Bitmap mBitmap = CodeUtils.createImage(item.getOrderCode(), 400, 400, null);
                                QRCodeDialog qrCodeDialog = DialogController.showQRCodeDialog(mActivity, mBitmap);
                                orderCode = item.getOrderCode();
                                checkUserCouponIsSuccess(qrCodeDialog);
                            }
                        });
                    }
                }
            }
        };
        recycler_view.setLayoutManager(new LinearLayoutManager(mActivity));
        recycler_view.setAdapter(commonAdapter);


    }

    private void checkUserCouponIsSuccess(QRCodeDialog qrCodeDialog) {
        if (qrCodeDialog == null || !qrCodeDialog.isShowing() || !mActivityIsShow) {
            return;
        }
        addDisposableIoMain(orderService.checkUserCouponIsSuccess(orderCode), new DefaultConsumer<String>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<String> result) {
                if (result.getData().equals("1")) {
                    qrCodeDialog.dismiss();
                    DialogController.showMustConfirmDialog(mActivity, result.getMessage(), (View v) -> {
                    });
                } else {
                    new Handler().postDelayed(() -> {
                        checkUserCouponIsSuccess(qrCodeDialog);
                    }, 1500L);
                }
            }
        });
    }

    @OnClick({R.id.apply_refund_btn, R.id.call_phone_iv, R.id.rl_merchant})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.apply_refund_btn:
                if (applyRefundBtnCanClick) {
                    Intent intent = new Intent(mActivity, ApplyRefundActivity.class);
                    intent.putExtra("order_id", order_id);
                    startActivity(intent);
                } else {
                    showToast("退款中，请稍后");
                }
                break;
            case R.id.call_phone_iv:
                PhoneUtil.callPhone(mActivity, orderDetail.getShopName(),
                        "电话号码：" + orderDetail.getShopPhone(),
                        orderDetail.getShopPhone());

                break;
            case R.id.rl_merchant:
                Intent intent = new Intent(this, ShopDetailActivity.class);
                intent.putExtra("shopId", orderDetail.getShopId());
                startActivity(intent);
                break;
        }
    }

    @OnClick(R.id.ll_goto_bill)
    public void gotoBill(View view) {
//        if (orderDetail.getOrderState() == 2) {
//            ll_goto_bill.setVisibility(View.GONE);
//    }
//            qr_code_iv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (dupCommit()) return;
//                                /*Intent intent = new Intent(mActivity, WatchCouponQRCodeActivity2.class);
//                                intent.putExtra("orderCode", item.getOrderCode());
//                                startActivity(intent);*/
//                    Bitmap mBitmap = CodeUtils.createImage(orderDetail.getOrderCode(), 400, 400, null);
//                    DialogController.showQRCodeDialog(mActivity, mBitmap);
//                    orderCode = orderDetail.getOrderCode();
//                    Handler handler = new Handler();
//                    Runnable runnable = new Runnable() {
//                        @Override
//                        public void run() {
//                            handler.postDelayed(this, 2000);
//                            checkUserCouponIsSuccess();
//                        }
//                    };
//                    //如果需要关闭该定时器调用
//                    handler.removeCallbacks(runnable);
//                }
//            });

        Intent intent = new Intent();
        intent.putExtra("shopId", orderDetail.getShopId() + "");
        intent.putExtra("couponId", userOrderExtraDetailList.get(0).getItemId() + "");
        startActivity(DiscountPayBillActivity.class, intent);
    }

    public void loadData() {
        addDisposableIoMain(orderService.getUserOrderDetail(order_id), new DefaultConsumer<OrderDetail>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<OrderDetail> result) {
                orderDetail = result.getData();
                shop_name_tv.setText(orderDetail.getShopName());
                shop_address_tv.setText(orderDetail.getShopAddress());
                add_order_time_tv.setText(TimeUtil.timeStamp2Date(orderDetail.getCreate() + "", "yyyy-MM-dd HH:mm"));
                user_phone_tv.setText(!TextUtils.isEmpty(orderDetail.getUserPhone()) ? orderDetail.getUserPhone() : "");
                num_tv.setText(orderDetail.getNum() + "张");
                single_price_tv.setText(((orderDetail.getFinalPrice()) / (orderDetail.getNum())) + "");
                real_price_tv.setText("¥" + orderDetail.getFinalPrice());
                addDisposableIoMain(orderService.getUserExOrderDetail(order_id), new DefaultConsumer<List<UserOrderExtraDetail>>(mApplication) {
                    @Override
                    public void operateSuccess(BaseResult<List<UserOrderExtraDetail>> result) {
                        userOrderExtraDetailList.clear();
                        if (result.getData().get(0).getType() == Constant.GOODS_TYPE_REPLACE_MONEY) {
                            coupon_type_tv.setText("代金券");
                        } else if (result.getData().get(0).getType() == Constant.GOODS_TYPE_GROUP_BUY) {
                            coupon_type_tv.setText("团购券");
                        } else if (result.getData().get(0).getType() == Constant.GOODS_TYPE_SECOND_KILL) {
                            coupon_type_tv.setText("秒杀券");
                        } else if (result.getData().get(0).getType() == Constant.GOODS_TYPE_SPELLING_GROUP) {
                            coupon_type_tv.setText("拼团券");
                        }
                        goods_name_tv.setText(result.getData().get(0).getItemName());
                        if (Constant.GOODS_TYPE_SECOND_KILL == result.getData().get(0).getType()
                                || Constant.GOODS_TYPE_SPELLING_GROUP == result.getData().get(0).getType()) {
                            apply_refund_btn.setVisibility(View.GONE);
                        }
                        userOrderExtraDetailList.addAll(result.getData());
                        commonAdapter.notifyDataSetChanged();
                    }
                });
                helper.showContent();
            }
        });
    }


    @Subscribe
    public void onEventHandle(RefundEvent refundEvent) {
        applyRefundBtnCanClick = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
